package com.example.gpsparse.dao;

import com.example.gpsparse.model.GpsData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.transaction.Transactional;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * GPS数据访问层
 */
@Repository
public class GpsDataDao {

    @Autowired
    private GpsDataRepository gpsDataRepository;

    /**
     * 查询未处理的GPS数据
     *
     * @param limit 限制条数
     * @return GPS数据列表
     */
    public List<GpsData> findUnprocessedGpsData(int limit) {
        List<GpsData> dataList = gpsDataRepository.findByStatusOrderByIdAsc(0);
        return dataList.size() > limit ? dataList.subList(0, limit) : dataList;
    }

    /**
     * 批量更新GPS数据的地址信息
     *
     * @param gpsDataList GPS数据列表
     * @return 更新的记录数
     */
    @Transactional
    public int batchUpdateGpsAddress(List<GpsData> gpsDataList) {
        List<GpsData> savedList = gpsDataRepository.saveAll(gpsDataList);
        return savedList.size();
    }

    /**
     * GPS数据行映射器
     */
    private static class GpsDataRowMapper implements RowMapper<GpsData> {
        @Override
        public GpsData mapRow(ResultSet rs, int rowNum) throws SQLException {
            return GpsData.builder()
                    .id(rs.getLong("id"))
                    .latitude(rs.getDouble("latitude"))
                    .longitude(rs.getDouble("longitude"))
                    .status(rs.getInt("status"))
                    .build();
        }
    }
}